 package com.gmrz.uaf.db;

 import com.gmrz.uaf.common.UAFRuntimeException;
 import com.gmrz.uaf.protocol.v1.processor.exception.UAFErrorCode;
 import com.gmrz.util.db.DBUtil;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;

 import java.sql.Connection;
 import java.sql.SQLException;
 
 public class UAFDBConnectionMgr
 {
   private static final Logger LOG = LogManager.getLogger(UAFDBConnectionMgr.class);
 
   private static UAFDBConnectionProvider connectionProvider = null;
 
   public static void init()
   {
     if (connectionProvider == null)
       connectionProvider = getConnectionProvider();
   }
 
   public static Connection getConnection()
     throws SQLException
   {
     if (connectionProvider == null) {
       connectionProvider = getConnectionProvider();
     }
     return connectionProvider.getConnection();
   }
 
   public static Connection getConnection(boolean autoCommit) throws SQLException {
     Connection conn = getConnection();
     if (conn != null)
       conn.setAutoCommit(autoCommit);
     else {
       LOG.error("Failed to connect to database ");
     }
     return conn;
   }

   public static Connection getLogConnection() throws SQLException{
     if (connectionProvider == null) {
       connectionProvider = getConnectionProvider();
     }
     return connectionProvider.getLogConnection();
   }


   public static Connection getLogConnection(boolean autoCommit) throws SQLException {
     Connection conn = getLogConnection();
     if (conn != null)
       conn.setAutoCommit(autoCommit);
     else {
       LOG.error("Failed to connect to database ");
     }
     return conn;
   }
 
   private static UAFDBConnectionProvider getConnectionProvider()
   {
     UAFDBConnectionProvider cp = new UAFDatasourceConnection();
     if (!testConnection(cp)) {
       LOG.error("Failed to connect to database for datasource [{}]",
               "jdbc/fidods");

       throw new UAFRuntimeException(UAFErrorCode.DB_DATABASE_CONNECTION_ERROR.toString());
     }
     return cp;
   }
 
   private static boolean testConnection(UAFDBConnectionProvider cp) {
     Connection conn = null;
     try {
       conn = cp.getConnection();
       if (conn == null) {
         LOG.error("Failed to connect to database jdbc/fidods");
         return false;
       }
       LOG.info("Successfully connected to database [{}].",
               conn.getMetaData().getDatabaseProductName());
         //FIDOLOG
       conn = cp.getLogConnection();
       if(conn==null){
         LOG.info("Failed to connect to log database jdbc/fidologds");
         return false;
       }
       return true;
     }
     catch (SQLException sqle) {
       LOG.error("Failed to connect to database, ", sqle);
       return false;
     } finally {
       DBUtil.close(conn);
     }
   }
 }
